/*
cron "0 9 * * *" autoSignin.js, tag=恩山论坛签到
*/

const axios = require('axios')
const { initInstance, getEnv, updateCkEnv } = require('./qlApi.js')
const notify = require('./sendNotify')

const updateAccesssTokenURL = 'https://auth.aliyundrive.com/v2/account/token'
const signinURL =
  'https://www.right.com.cn/FORUM/misc.php?mod=patch&action=ipnotice&_r=0.2669866035758326&inajax=1&ajaxtarget=ip_notice'
const rewardURL =
  'https://member.aliyundrive.com/v1/activity/sign_in_reward?_rx-s=mobile'

// 使用 refresh_token 更新 access_token
function updateAccesssToken(queryBody, remarks) {
  const errorMessage = [remarks, '更新 access_token 失败']
  return axios(updateAccesssTokenURL, {
    method: 'POST',
    data: queryBody,
    headers: { 'Content-Type': 'application/json' }
  })
    .then(d => d.data)
    .then(d => {
      const { code, message, nick_name, refresh_token, access_token } = d
      if (code) {
        if (
          code === 'RefreshTokenExpired' ||
          code === 'InvalidParameter.RefreshToken'
        )
          errorMessage.push('refresh_token 已过期或无效')
        else errorMessage.push(message)
        return Promise.reject(errorMessage.join(', '))
      }
      return { nick_name, refresh_token, access_token }
    })
    .catch(e => {
      errorMessage.push(e.message)
      return Promise.reject(errorMessage.join(', '))
    })
}

//签到列表
function sign_in(access_token, remarks) {
  const sendMessage = [remarks]
  return axios(signinURL, {
    method: 'GET',
    data: {
      mod: 'patch',
      action: 'ipnotice',
      _r: '0.2669866035758326',
      inajax: 1,
      ajaxtarget: 'ip_notice'
    },
    headers: {
      cookie: access_token,
      'Content-Type': 'text/xml; charset=utf-8'
    }
  })
    .then(response => {
      console.log(response.status)
      if (response.status === 200) {
        sendMessage.push('签到成功')
        return Promise.reject(sendMessage.join(', '))
      }
      sendMessage.push('签到失败', response.statusText)
      return Promise.reject(sendMessage.join(', '))
    })
}

// 领取奖励
function getReward(access_token, signInDay) {
  return axios(rewardURL, {
    method: 'POST',
    data: { signInDay },
    headers: {
      authorization: access_token,
      'Content-Type': 'application/json'
    }
  })
    .then(d => d.data)
    .then(json => {
      if (!json.success) {
        return Promise.reject(json.message)
      }

      return json.result
    })
}

// 获取环境变量
async function getRefreshToken() {
  let instance = null
  try {
    instance = await initInstance()
  } catch (e) {
  }

  let refreshToken = process.env.enSanCookie || []

  try {
    if (instance) refreshToken = await getEnv(instance, 'enSanCookie')
  } catch (e) {
  }

  let refreshTokenArray = []

  if (Array.isArray(refreshToken)) refreshTokenArray = refreshToken
  else if (refreshToken.indexOf('&') > -1)
    refreshTokenArray = refreshToken.split('&')
  else if (refreshToken.indexOf('\n') > -1)
    refreshTokenArray = refreshToken.split('\n')
  else refreshTokenArray = [refreshToken]

  if (!refreshTokenArray.length) {
    console.log('未获取到enSanCookie, 程序终止')
    process.exit(1)
  }

  return {
    instance,
    refreshTokenArray
  }
}

!(async () => {
  const { instance, refreshTokenArray } = await getRefreshToken()

  const message = []
  let index = 1
  for await (refreshToken of refreshTokenArray) {
    let remarks = `账号${index}`

    // 更新环境变量
    if (instance) {
      let params = {
        name: refreshToken.name,
        value: refresh_token,
        remarks: refreshToken.remarks || nick_name // 优先存储原有备注信息
      }
      // 新版青龙api
      if (refreshToken.id) {
        params.id = refreshToken.id
      }
      // 旧版青龙api
      if (refreshToken._id) {
        params._id = refreshToken._id
      }
      await updateCkEnv(instance, params)
    }
    try {
      const sendMessage = await sign_in(refreshToken, remarks)
      console.log(sendMessage)
      console.log('\n')
      message.push(sendMessage)
    } catch (error) {
      console.log(error)
    }
    index++
  }
  await notify.sendNotify(`恩山论坛签到`, message.join('\n'))
})()
